import React, { useRef, useState, useEffect } from 'react';
import { Row, Col, Table, message, Button, Modal, Form, Input, Select,Radio} from 'antd';
import { getNewJyr,getBkStockList,getNewBkList,removeMonitorStock,updateMonitorStock,addMonitorStock,refreshMonitorStock } from '../../service/apis/quotation';
import './index.css';
import { StockType } from '../../service/config';
import KLines from '@/components/klines';


const Stocks: React.FC = () => {
  

  const [tableData, setTableData] = useState([]);
  const [curJyr, setCurJyr] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [isAddMode, setIsAddMode] = useState(false);
  const [form] = Form.useForm();
  const [bkMap, setBkMap] = useState(new Map());
  const [selectedBk, setSelectedBk] = useState({});

  const [isStockModalVisible, setIsStockModalVisible] = useState(false);
  const [selectedStockData, setSelectedStockData] = useState(null);
  

  const columns = [
    {
      title: '代码',
      align: 'center',
      dataIndex: 'code',
      key: 'code',
      render: (text: string, record: any) => (
          <div>
            <Button type="link"  onClick={() => handleStockClick(record.code)}>
              {record.code}
            </Button>
          </div>
      ),
    },
    {
      title: '股票',
      align: 'center',
      dataIndex: 'name',
      key: 'name',
      render: (text: any, record: any) => {
        const hasHighType = record.type === 'HIGH';
        const hasFrontType = record.type === 'HIGH_FRONT';
        const icon = hasHighType ? <sup style={{ color: '#cf1322' }}>★★</sup> : hasFrontType ? <sup style={{ color: '#FFA07A' }}>★</sup> : '';
        const fontWeight = hasHighType||hasFrontType ? 'bold' : 'normal';
        return (
          <span style={{ color: hasHighType ? '#cf1322' : hasFrontType? '#FFA07A':'', fontWeight }}>
            {text}
            {icon}
        </span>
        );
      },
    },
    
    {
      title: '涨幅',
      align: 'center',
      dataIndex: 'zqxy',
      key: 'zqxy',
      sorter: (a, b) => a.zqxy - b.zqxy,
      render: (text: number, record: any) => {
        let displayText = '';
        let color = '';
        displayText = text !== null && text !== undefined ? Number(text).toFixed(2) + '%' : '-';
        color = text > 0 ? '#cf1322' : '#3f8600';
        return <span style={{ color }}>{displayText}</span>;
      },
    },
    {
      title: '连扳描述',
      align: 'center',
      dataIndex: 'lbDesc',
      key: 'lbDesc',
      render: (text) => (
        <span style={{ color: text !== null && text !== undefined ? '#cf1322' : '#3f8600' }}>
          {text}
        </span>
      ),
    },
    {
      title: '涨停原因',
      align: 'center',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '封板资金',
      align: 'center',
      dataIndex: 'fbValue',
      key: 'fbValue',
      sorter: (a, b) => a.fbValue - b.fbValue,
      render: (text: number) => <span>{Number(text/100000000).toFixed(3)}亿</span>,
    },

    {
      title: '开盘溢价',
      align: 'center',
      dataIndex: 'kpYj',
      key: 'kpYj',
      sorter: (a, b) => a.kpYj - b.kpYj,
      render: (text: number) => {
        let color = text > 0 ? '#cf1322' : '#3f8600';
        return <span style={{ color }}>{Number(text).toFixed(2)}</span>;
      },
    },
    {
      title: '亏钱效应',
      align: 'center',
      dataIndex: 'kqxy',
      key: 'kqxy',
      sorter: (a, b) => a.kqxy - b.kqxy,
      render: (text: number) => {
        let color = text > 0 ? '#cf1322' : '#3f8600';
        return <span style={{ color }}>{Number(text).toFixed(2)}</span>;
      },
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text, record) => (
        <>
          <Button type="link" onClick={() => handleRemoveMonitor(record.bkCode,record.code)}>删除</Button>
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
        </>
      ),
    },
  ];

  const fetchTableData = (bk) => {
    getBkStockList({ jyr: curJyr,bkcode:bk.code }).then(data => {
      setTableData(data);
    }).catch(error => console.error('Error fetching monitor data:', error));
  };

  const handleRemoveMonitor = (bkCode,code) => {
    // 移除监控的逻辑
    removeMonitorStock({bkCode: bkCode,code: code}).then(() => {
      message.success('移除成功');
      fetchTableData(selectedBk);
    }).catch(error => console.error('Error removing monitor stock:', error));
  };

  const handleEdit = (record) => {
    setIsAddMode(false);
    setEditingRecord(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };
  const handleAdd = () => {
    setIsAddMode(true);
    form.resetFields();
    setIsModalVisible(true);
  };
  const onBkSeletedChange = (e) => {
    setSelectedBk(bkMap.get(e.target.value));
    fetchTableData(bkMap.get(e.target.value));
  }
  const handleRefresh = () => {
    const now = new Date();
    const hours = now.getHours();
    if (hours >= 15) {
      // 下午 3 点之后才能刷新
      refreshMonitorStock().then(() => {
        message.success('刷新成功');
        fetchTableData(selectedBk);
      }).catch(error => console.error('Error removing monitor stock:', error));
    } else {
      message.warning('只能在下午 3 点之后刷新数据');
    }
  }
  const handleOk = () => {
    // 新增股票信息的逻辑
    form.validateFields().then(values => {
      if (isAddMode) {
        // 新增股票信息的逻辑
        addMonitorStock({
          jyr: curJyr,
          bkcode: values.bkCode,
          code: values.code,
          name:values.name,
          range: values.range,
          type: values.type,
          lbdesc: values.lbDesc,
          remark: values.remark
        }).then(() => {
          message.success('新增成功');
          setIsModalVisible(false);
          fetchTableData(selectedBk);
        });
      } else {
        // 更新股票信息的逻辑
        updateMonitorStock({
          jyr: curJyr,
          bkcode: editingRecord.bkCode,
          code: editingRecord.code,
          range: values.range,
          type: values.type,
          nbkcode: values.bkCode,
          lbdesc: values.lbDesc,
          remark: values.remark
        }).then(() => {
          message.success('更新成功');
          setIsModalVisible(false);
          fetchTableData(selectedBk);
        });
      }
    }).catch(info => {
      console.log('验证失败:', info);
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const handleStockClick = (code: any) => {
    setSelectedStockData(code);
    setIsStockModalVisible(true);
  };

  const handleModalClose = () => {
    setIsStockModalVisible(false);
    setSelectedStockData(null);
  };

  useEffect(() => {
    getNewJyr().then(date => {
        setCurJyr(date);
        getNewBkList({ jyr: date }).then(data => {
          setSelectedBk(data[0]);
          const bkMap = new Map();
          data.forEach(item => {
            bkMap.set(item.code, item);
          });
          setBkMap(bkMap);
          getBkStockList({ jyr: date,bkcode:data[0].code }).then(data => {
            setTableData(data);
          }).catch(error => console.error('Error fetching monitor data:', error));
        }).catch(error => console.error('Error fetching monitor data:', error));
        
      })
      .catch(error => console.error('Error fetching trading date:', error));

  }, []);

  return (
    <div className="pl-4">
      <div  style={{ display: 'flex', gap: '16px', marginBottom: '16px' }}>
        <Button type="primary" onClick={handleAdd}>新增</Button>
        <Button type="primary" onClick={handleRefresh}>刷新收盘数据</Button>
      </div >
      <Row className="row-spacing">
        <Radio.Group onChange={onBkSeletedChange}  value={selectedBk.code}>
             {Array.from(bkMap.entries()).map(([code, item]) => (
                <Radio key={code} value={code}>
                  {item.name}
                </Radio>
              ))}
        </Radio.Group>
      </Row> 
      <Row className="row-spacing">
        <Col span={24}>
          <Table
            columns={columns}
            dataSource={tableData}
            pagination={false}
            rowKey="stockCode"
            className="custom-table-cell"
          />
        </Col>
      </Row>
      <Modal
        title={isAddMode ? "新增股票信息" : "编辑股票信息"}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          {isAddMode && (
            <Form.Item
              name="code"
              label="股票代码"
              rules={[{ required: true, message: '请输入股票代码' }]}
            >
              <Input />
            </Form.Item>
            
          )}
          {isAddMode && (
            <Form.Item
            name="name"
            label="股票名称"
            rules={[{ required: true, message: '请输入股票名称' }]}
          >
            <Input />
          </Form.Item>
          )}
          <Form.Item
            name="type"
            label="地位"
            rules={[{ required: true, message: '请输入地位' }]}
          >
             <Select>
              {Object.entries(StockType).map(([key, value]) => (
                <Option key={key} value={key}>
                  {value}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="lbDesc"
            label="连扳描述"
            rules={[{ message: '请输入连扳描述' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="range"
            label="排序信息"
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="bkCode"
            label="板块信息"
            rules={[{ required: true, message: '请输入板块信息' }]}
          >
            <Select>
              {Array.from(bkMap.entries()).map(([code, item]) => (
                <Option key={code} value={code}>
                  {`${item.name}`}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="remark"
            label="题材备注"
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="股票K线走势图"
        visible={isStockModalVisible}
        onCancel={handleModalClose}
        footer={null}
        width={800}
      >
        {selectedStockData && <KLines code={selectedStockData} />}
      </Modal>
    </div>
  );
};

export default Stocks;